package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.commonunsafe;

import com.ziyucoding.springboot.labs.lab4.concurrentdemo.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * DateFormat 实例1
 *
 * @author ziyucoding
 * @date 2022-10-26
 **/
@Slf4j
@ThreadSafe
public class DateFormatExample2 {

    /**
     * 请求总数
     */
    private static int requestTotal = 5000;

    /**
     * 同时并发执行的线程数
     */
    private static int threadTotal = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(requestTotal);

        for (int i = 0; i < requestTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("发生异常", e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        countDownLatch.await();
        executorService.shutdown();
    }

    /**
     * 更新
     *
     * @return void
     **/
    private static void update() {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            simpleDateFormat.parse("2022-10-26");
        } catch (ParseException e) {
            log.error("simpleDateFormat.parse exception", e);
        }
    }

}
